package cn.yangliu.jwt.handler;

import cn.yangliu.jwt.comm.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 杨柳
 * @date 2019-04-18
 */
public interface IHandler {

    /**
     * 默认的认证异常
     * @param request 请求
     * @param response 响应
     * @param ex 异常
     * @param status 状态码
     * @param msg 消息
     * @param data 数据
     * @throws IOException IO异常
     * @throws ServletException Servlet异常
     */
    default void handle(HttpServletRequest request, HttpServletResponse response, Exception ex, HttpStatus status, String msg, Object data) throws IOException, ServletException {
        response.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        JsonResult result = new JsonResult<>(status, msg, data);
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(result));
        writer.flush();
        writer.close();
    }

    /**
     * 默认的认证异常
     * @param request 请求
     * @param response 响应
     * @param ex 异常
     * @param status 状态码
     * @param msg 消息
     * @throws IOException IO异常
     * @throws ServletException Servlet异常
     */
    default void handle(HttpServletRequest request, HttpServletResponse response, Exception ex, HttpStatus status, String msg) throws IOException, ServletException {
        handle(request, response, ex, status, msg, null);
    }

}
